#include "StdAfx.h"
#include "ApproachCalcThread.h"

#include <boost/bind.hpp>
#include "Trajectory.h"
#include "EphemParam.h"

CApproachCalcThread::CApproachCalcThread(TrajParam::Ptr pTrajParam)
{
	m_pTrajParam = pTrajParam;
	m_pThread = apBoostThread(new boost::thread(boost::bind(&CApproachCalcThread::do_work, this)));
}

CApproachCalcThread::~CApproachCalcThread(void)
{
	m_pThread->join();
}

void CApproachCalcThread::Wait()
{
	m_pThread->join();
}

bool CApproachCalcThread::IsDone(int nWaitMilliSec)
{
	boost::posix_time::time_duration waitPeriod;
	waitPeriod = boost::posix_time::milliseconds(nWaitMilliSec);
	return m_pThread->timed_join(waitPeriod);
}

LPCTSTR CApproachCalcThread::GetErrorStr() const
{
	return (m_strError.IsEmpty())? (LPCTSTR)NULL: m_strError;
}

void CApproachCalcThread::do_work()
{
	m_strError.clear();

	if(m_pTrajParam->pApproachHolder == NULL)
		return;

	try
	{
		CEphemParam ephemParam;
		CTrajectory trajectory(ephemParam.GetCurrentEphemPath(), m_pTrajParam->dParamVal);

		Body body;
		body.GM = 0.0;
		COrbitElemTransform::ElemToCoord( 0.0, 0.0, 0.0, m_pTrajParam->elem, body.x, body.v);

		ListApproachPtr approachList = trajectory.Move(m_pTrajParam->dStart, m_pTrajParam->dEnd, body, NULL);
		CTraceApproaches::Ptr trace( new CTraceApproaches(m_pTrajParam->dParamVal, approachList) );
		m_pTrajParam->pApproachHolder->AppendTraceApproaches(trace);
	}
	catch(const CCustomException &e)
	{
		m_strError = e.GetErrorStr();
	}
	catch(...)
	{
		m_strError = _T("Unknown error");
	}
}